﻿using System;
using System.Collections.Generic;

namespace Hsenl.Network {
    public class UdpCollecter {
        private readonly List<IUdpReceiver> _receivers = new(1);
        private readonly List<IUdpSender> _senders = new(1);

        public IUdpReceiver Receiver => this._receivers.Count > 0 ? this._receivers[0] : null;
        public IUdpSender Sender => this._senders.Count > 0 ? this._senders[0] : null;

        public IteratorList<IUdpReceiver> ForeachReceivers() {
            return new IteratorList<IUdpReceiver>(this._receivers);
        }

        public IteratorList<IUdpSender> ForeachSenders() {
            return new IteratorList<IUdpSender>(this._senders);
        }

        public void AddReceiver(IUdpReceiver receiver) {
            this._receivers.Add(receiver);
        }

        public void AddSender(IUdpSender sender) {
            this._senders.Add(sender);
        }

        public void ReceiveFromAsyncAll() {
            foreach (var receiver in this._receivers) {
                receiver.ReceiveFromAsync();
            }
        }

        public bool SendToAsync() {
            foreach (var sender in this._senders) {
                if (sender.SendToAsync())
                    return true;
            }

            return false;
        }

        public void Close(bool closeSocket) {
            foreach (var receiver in this._receivers) {
                receiver.Close(closeSocket);
            }

            foreach (var sender in this._senders) {
                sender.Close(closeSocket);
            }

            this._receivers.Clear();
            this._senders.Clear();
        }

        public void Dispose() {
            foreach (var receiver in this._receivers) {
                receiver.Dispose();
            }

            foreach (var sender in this._senders) {
                sender.Dispose();
            }

            this._receivers.Clear();
            this._senders.Clear();
        }
    }
}